package cn.tedu.blog.server.service.impl;


import cn.tedu.blog.server.pojo.entity.ArticleItem;
import cn.tedu.blog.server.pojo.vo.ArticleStandardVO;
import cn.tedu.blog.server.repo.SearchRepository;
import cn.tedu.blog.server.service.IArticleService;
import cn.tedu.blog.server.service.ISearchService;
import cn.tedu.blog.server.utils.JsonPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class SearchServiceImpl implements ISearchService {
    @Autowired
    private SearchRepository itemRepository;

    @Autowired
    private IArticleService articleService;

    @Override
    public void loadArticleByPage() {

        int i=1;     // 循环次数,0也是页码
        int pages=0; // 总页数,初始赋值为0(不赋值也可以)
        do{

            JsonPage<ArticleStandardVO> articles=articleService.getArticleByPage(i,5);
            List<ArticleItem> esArticles=new ArrayList<>();

            for(ArticleStandardVO article: articles.getList()){
                ArticleItem esArticle=new ArticleItem();
                BeanUtils.copyProperties(article,esArticle);

                esArticles.add(esArticle);
            }
            itemRepository.saveAll(esArticles);
            log.info("成功加载第{}页数据",i);
            pages=articles.getTotalPage();
            i++;
        }while(i<=pages);

    }

    @Override
    public JsonPage<ArticleItem> search(String keyword, Integer page, Integer pageSize) {

        Page<ArticleItem> articles = itemRepository.querySearch(keyword,
                 PageRequest.of(page - 1, pageSize));

        JsonPage<ArticleItem> jsonPage = new JsonPage<>();
        jsonPage.setPage(page);
        jsonPage.setPageSize(pageSize);
        jsonPage.setTotal(articles.getTotalElements());
        jsonPage.setTotalPage(articles.getTotalPages());
        jsonPage.setList(articles.getContent());
        return jsonPage;

    }
}
